package org.xserver.component.listener;

import java.util.ArrayList;
import java.util.Collection;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.handler.execution.ChannelDownstreamEventRunnable;
import org.jboss.netty.handler.execution.ChannelUpstreamEventRunnable;

public class XServerMemoryAwareThreadPoolExecutorStatus implements
		XServerMemoryAwareThreadPoolExecutorStatusMBean {
	private final XServerMemoryAwareThreadPoolExecutor pool;

	public XServerMemoryAwareThreadPoolExecutorStatus(
			XServerMemoryAwareThreadPoolExecutor pool) {
		this.pool = pool;
	}

	@Override
	public int getActiveThreads() {
		return pool.getPoolSize();
	}

	@Override
	public int getActiveTasks() {
		return pool.getActiveCount();
	}

	@Override
	public int getTotalTasks() {
		return pool.getTotalTasks();
	}

	@Override
	public int getQueuedTasks() {
		return pool.getQueue().size();
	}

	@Override
	public double getAverageTaskTime() {
		return pool.getAverageTaskTime();
	}

	@Override
	public String[] getActiveTaskNames() {
		return toStringArray(pool.getInProcessTasks());
	}

	@Override
	public String[] getQueuedTaskNames() {
		return toStringArray(pool.getQueue());
	}

	private String[] toStringArray(Collection<Runnable> collection) {
		ArrayList<String> list = new ArrayList<String>();
		for (Runnable r : collection) {
			String info = r.toString();
			if (r instanceof ChannelUpstreamEventRunnable) {
				ChannelEvent event = ((ChannelUpstreamEventRunnable) r)
						.getEvent();
				info = event.toString();
			} else if (r instanceof ChannelDownstreamEventRunnable) {
				ChannelEvent event = ((ChannelDownstreamEventRunnable) r)
						.getEvent();
				info = event.toString();
			}
			list.add(info);
		}

		return list.toArray(new String[0]);
	}

}
